export function arrayBufferToString(arr) {
	if (typeof arr === 'string') {
		return arr;
	}
	var dataview = new DataView(arr.data);
	var ints = new Uint8Array(arr.data.byteLength);
	for (var i = 0; i < ints.length; i++) {
		ints[i] = dataview.getUint8(i);
	}
	arr = ints;
	var str = '',
		_arr = arr;
	for (var i = 0; i < _arr.length; i++) {
		var one = _arr[i].toString(2),
			v = one.match(/^1+?(?=0)/);
		if (v && one.length == 8) {
			var bytesLength = v[0].length;
			var store = _arr[i].toString(2).slice(7 - bytesLength);
			for (var st = 1; st < bytesLength; st++) {
				store += _arr[st + i].toString(2).slice(2);
			}
			str += String.fromCharCode(parseInt(store, 2));
			i += bytesLength - 1;
		} else {
			str += String.fromCharCode(_arr[i]);
		}
	}
	return str;
}

export function buf2hex(arrayBuffer) {
	return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}



export function base64Decode(input) {
	const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

	// 去除填充字符 '='
	input = input.replace(/=/g, '');

	// 将每个 Base64 字符转换为 6 位二进制
	let binaryString = '';
	for (let i = 0; i < input.length; i++) {
		const index = base64Chars.indexOf(input.charAt(i)); // 查找字符的位置
		binaryString += index.toString(2).padStart(6, '0'); // 将位置转换为 6 位二进制
	}

	// 每 8 位一个字节，转换为字节
	let decodedBytes = [];
	for (let i = 0; i < binaryString.length; i += 8) {
		const byte = binaryString.slice(i, i + 8);
		decodedBytes.push(parseInt(byte, 2)); // 将二进制转为字节
	}

	// 将字节数组转换为 UTF-8 字符串
	let decodedString = new TextDecoder().decode(new Uint8Array(decodedBytes));

	return decodedString;
}

export function jm(data) {


	let txt;
	// 进行判断返回的对象是Uint8Array（开发者工具）或者ArrayBuffer（真机）
	// 1.获取对象的准确的类型
	const type = Object.prototype.toString.call(data); // Uni8Array的原型对象被更改了所以使用字符串的信息进行判断。
	if (type === "[object Uint8Array]") {

		txt = decodeURIComponent(escape(String.fromCharCode(...data)))
	} else if (data instanceof ArrayBuffer) {
		// 将ArrayBuffer转换为Uint8Array

		const uint8Array = new Uint8Array(data);
		txt = decodeURIComponent(escape(String.fromCharCode(...uint8Array)))
	}
	// 打印编码的结果
	return txt;

}